package myJs.cps

import cats.effect.SyncIO
import japgolly.scalajs.react._
import japgolly.scalajs.react.util.EffectCatsEffect._
import japgolly.scalajs.react.vdom.all._
import myJs.Implicits._
import myJs.Utils._
import myJs.myPkg.Hooks._
import myJs.myPkg.reactHookForm._
import myJs.tool.Tool
import myJs.tool.Tool._

import scala.collection.immutable.SeqMap

/** Created by yz on 3/11/2020
  */
object RSelectMulInlineCp {

  case class Props(
      value: List[String],
      onChange: List[String] => SyncIO[Unit],
      label: String,
      name: String = "",
      optionMap: SeqMap[String, String],
      questionInfo: String = "",
      show: Boolean = true,
      registerOptions: RegisterOptions = RegisterOptions(),
      labelWidth: Int = 2,
      inputWidth: Int = 4
  ) {
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val Component = ScalaFnComponent[Props] { props =>
    val useForm = ReactHookForm.useFormContext()
    useEffect(
      SyncIO {
        Tool.popover
        ()
      },
      List()
    )

    val hasErrorCls = if (useForm.formState.errors.deepDefinedAt(props.name)) "has-error" else ""
    val displayStr = if (props.show) "block" else "none"
    div(
      paddingRight := "0px",
      paddingLeft := "0px",
      display := displayStr,
      className := s"form-group ${hasErrorCls}",
      label(
        className := s"control-label col-sm-${props.labelWidth}",
        s"${props.label}",
        if (props.questionInfo.nonBlank) {
          span(
            className := "",
            a(
              `type` := "button",
              className := "selfQuestion",
              title := messages("note"),
              dataContainer := "body",
              dataToggle := "popover",
              dataHtml := "true",
              dataPlacement := "left",
              dataContent := props.questionInfo,
              i(className := "fa fa-question-circle-o")
            )
          )
        } else EmptyVdom,
        ":"
      ),
      div(
        className := s"col-sm-${props.inputWidth}",
        PureRSelectMulCp
          .Props(
            name = props.name,
            value = props.value,
            onChange = props.onChange,
            optionMap = props.optionMap,
            registerOptions = props.registerOptions
          )
          .render
      )

    )

  }

}
